<?php
/**
 * Copyright (c) 2006-2007, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright    Copyright (c) 2006-2007, PORTALIER Julien
 * @link         http://feather-cm.google.com/
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class Invitation extends ActiveRecord
{
	function beforeValidate()
	{
		if (empty($this->validate))
		{
			$this->validate = array(
				'email' => array(
					Valid::NotEmpty => _('Please fill in the email of the person to invite.'),
					Valid::Email    => _("Invalid email.")
				),
				'member_id' => array(
					Valid::NotEmpty => _('Someone must be sending the invitation.')
				)
			);
		}
		return true;
	}
	
	/**
	 * Returns the list of invitations for $member_id.
	 */
	function getList($member_id)
	{
		$this->conditions(array('member_id' => $member_id, 'md5' => '-! IS NOT NULL'));
		$this->process = Q_PROCESS_LITE;
		return $this->findAll('*', null, null, -1);
	}
	
	/**
	 * Returns weither the code exists, or not.
	 */
	function getField($field, $md5)
	{
		$this->condition('md5', $md5);
		return $this->field($field, null, -1);
	}
	
	/**
	 * Creates an unique invitation code for $member_id.
	 */
	function create($member_id)
	{
		# data
		$this->id   = null;
		$this->data['Invitation']['member_id'] = $member_id;
		
		# generates unique identifier
		while(true)
		{
			$this->data['Invitation']['md5'] = strtoupper(substr(md5(uniqid()), 0, 10));
			$check = $this->getField('id', $this->data['Invitation']['md5']);
			
			# no such identifier already? let's go for it!
			if (empty($check))
				break;
		}
		
		return $this->save();
	}
	
	/**
	 * Erases an invitation code.
	 */
	function erase($md5)
	{
		$this->id = $this->getField('id', $md5);
		return $this->saveField('md5', null);
	}
}
?>